// 发表评论的功能
import React from "react";
import './index.css'
class PingLun extends React.Component{

    state = {
        userName: '',
        userCom: '',
        contentList: []
    }
    // 渲染评论
    renderContent() {
        const { contentList } = this.state;
        if(contentList.length === 0) {
            return (
                <p>暂时无评论，请添加</p>
            )
        } else {
            return (
                <ul>
                    {contentList.map( item => (
                        <li key={item.id}>
                            <p>名字：{item.name}</p>
                            <p>评论：{item.com}</p>
                        </li>
                    ))}
                </ul>
            )
        }
    }
    // 处理表单
    handleForm = e => {
     let { name,value } =  e.target;
     this.setState({
        [name]: value
     })
    }
    // 发表评论
    addComs = () => {
     const { userName,userCom, contentList } =  this.state;
    //  非空校验
    if (userName.trim() === '' || userCom.trim() === '') {
        alert('请输入内容');
        return;
    }
     const newComs = [
       {
        id:Math.random(),
        name: userName,
        com: userCom
       }, ...contentList
     ]
     console.log(newComs);
    //  清空文本框
     this.setState({
        userName: '',
        userCom: '',
        contentList: newComs
     })
    }
    render() {
        let { userName, userCom } = this.state;
        return (
            <div className="boredr">
                <div className="header">
                    <input type="text" placeholder="请输入评论人" value={userName} name="userName" onChange={this.handleForm}/>
                    <br/>
                    <textarea cols="30" rows="10" placeholder="请输入评论内容" value={userCom} name="userCom" onChange={this.handleForm}></textarea>
                    <br/>
                    <button onClick={this.addComs}>发表评论</button>
                </div>
                <div className="content">
                    {this.renderContent()}
                </div>
            </div>
        )
    }
}
export default PingLun;